import * as React from "react";
import { Form, Input, Modal } from "antd";
import { FormComponentProps } from "antd/lib/form";

interface INewRole {
  name: string;
  description: string;
}

interface IProps {
  title: string;
  visible: boolean;
  role?: INewRole;
  onOk: (newRole: INewRole) => void;
  onCancel: () => void;
  afterClose: () => void;
}

class RoleModalBase extends React.PureComponent<FormComponentProps & IProps> {
  state = {
    role: {
      name: "",
      description: ""
    }
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.role) {
      this.props.form.resetFields();
    }
  }

  nameInputHandler = e => {
    const { role } = this.state;
    this.setState({
      role: {
        ...role,
        name: e.target.value
      }
    });
  };

  descriptionInputHandler = e => {
    const { role } = this.state;
    this.setState({
      role: {
        ...role,
        description: e.target.value
      }
    });
  };

  render() {
    const { title, visible, onOk, onCancel, afterClose } = this.props;
    const { role } = this.state;
    const { getFieldDecorator } = this.props.form;

    return (
      <Modal
        visible={visible}
        title={title}
        okText="新建"
        onCancel={onCancel}
        onOk={() => onOk(role)}
        afterClose={afterClose}
      >
        <Form layout="vertical">
          <Form.Item label="角色名">
            {getFieldDecorator("name", {
              rules: [{ required: true, message: "角色名不能为空" }]
            })(<Input />)}
          </Form.Item>
          <Form.Item label="描述">
            {getFieldDecorator("description")(<Input />)}
          </Form.Item>
        </Form>
      </Modal>
    );
  }
}

export const RoleModal = Form.create()(RoleModalBase);
